import {
  Controller,
  Post,
  Body,
  Get,
  BadRequestException,
  UseGuards,
} from '@nestjs/common'
import { UserEntity } from 'src/entities/user.entity'
import { AuthService } from './auth.service'
import {
  createDto,
  createWxDto,
  loginDto,
  updateDto,
  wxLoginDto,
} from './dto/user.dto'
import { AuthGuard } from '@nestjs/passport'
import { CurrentUser } from 'src/common/decorator/user.decorator'
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger'
import { NoAuth } from 'src/utils/noAuth'
import axios from 'axios'
import configuration from 'src/config/configuration'
import { decryptData } from 'src/utils/utils'

@Controller('auth')
@ApiTags('auth')
export class AuthController {
  constructor(private authService: AuthService) {}
  @Post('register')
  @ApiOperation({ summary: '注册' })
  async register(@Body() body: createDto): Promise<UserEntity> {
    const [err, data] = await this.authService.register(body)
    if (!err) {
      return data
    } else {
      throw new BadRequestException('该用户已存在')
    }
  }
  @Post('login')
  @ApiOperation({ summary: '登陆' })
  @UseGuards(AuthGuard('local'))
  async login(
    @Body() body: loginDto,
    @CurrentUser() user: UserEntity,
  ): Promise<any> {
    return await this.authService.login(user)
  }

  @Get('user')
  @ApiBearerAuth()
  @ApiOperation({ summary: '获取用户详情' })
  async test1(@CurrentUser() user: UserEntity): Promise<any> {
    return user
  }

  @Post('update')
  @ApiBearerAuth()
  @ApiOperation({ summary: '更新用户信息' })
  async update(
    @Body() body: updateDto,
    @CurrentUser() user: UserEntity,
  ): Promise<any> {
    const [err, res] = await this.authService.update(body, user)
    if (!err) {
      return {
        code: 200,
        message: '保存成功',
      }
    } else {
      throw new BadRequestException('保存失败')
    }
  }

  @Post('wxLogin')
  @ApiOperation({ summary: '微信用户登陆' })
  @NoAuth()
  async wxLogin(@Body() body: wxLoginDto): Promise<any> {
    // 如果用户只传入code,则在表中查询获取openId对应用户,没有则返回空
    // 如果用户传入完整信息,则解密,并尝试通过手机号码进行绑定已有用户或新建用户
    // @ts-ignore

    if (body.iv && body.encryptedData) {
      const code2res = await axios.get(
        'https://api.weixin.qq.com/sns/jscode2session',
        {
          params: {
            appid: configuration().appId,
            secret: configuration().appSecret,
            js_code: body.code,
            grant_type: 'authorization_code',
          },
        },
      )

      const OpenId = code2res.data.openid
      let phoneNumber
      try {
        phoneNumber = decryptData(
          body.encryptedData,
          body.iv,
          // @ts-ignore
          code2res.data.session_key,
          configuration().appId,
        )
      } catch (error) {
        return '解密失败'
      }

      const findResult: UserEntity | null = await this.authService.findOneByMap(
        {
          phone: phoneNumber.phoneNumber,
        },
      )

      if (findResult) {
        const [err, updateResult] = await this.authService.update(
          {
            ...findResult,
            wxOpenid: OpenId,
          },
          findResult,
        )
        const loginResult = await this.authService.login(findResult)
        return loginResult
      } else {
        const [err, registerResult] = await this.authService.register({
          username: phoneNumber.phoneNumber,
          password: '123456',
          wxOpenid: OpenId,
          phone: phoneNumber.phoneNumber,
        })
        const loginResult = await this.authService.login(registerResult)
        return loginResult
      }
    } else {
      return '普通查询'
    }
    // return await this.authService.login()
  }

  // @Get('user')
  // @ApiOperation({ summary: '获取用户详情' })
  // @ApiBearerAuth()
  // async findUser(@CurrentUser() user: UserEntity): Promise<any> {
  //   return await this.authService.findUser(user)
  // }
}
